package com.hundsun.cprs.yyt.gateway.service.trade.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.Validate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.alibaba.fastjson.JSONObject;
import com.hundsun.cprs.yyt.common.base.BaseService;
import com.hundsun.cprs.yyt.common.enums.EnumAreaCode;
import com.hundsun.cprs.yyt.common.enums.EnumBusinessCode;
import com.hundsun.cprs.yyt.common.enums.EnumCommonCode;
import com.hundsun.cprs.yyt.common.exception.ServiceCodeException;
import com.hundsun.cprs.yyt.gateway.request.BussinessParamRequest;
import com.hundsun.cprs.yyt.gateway.request.DiliveryAddressRequest;
import com.hundsun.cprs.yyt.gateway.request.GoodsRequest;
import com.hundsun.cprs.yyt.gateway.request.PlateRequest;
import com.hundsun.cprs.yyt.gateway.request.ReturnGoodsRequest;
import com.hundsun.cprs.yyt.gateway.request.TradeMatchDetailRequest;
import com.hundsun.cprs.yyt.gateway.request.kuaidi100SynQueryDataRequest;
import com.hundsun.cprs.yyt.gateway.response.BaseResponse;
import com.hundsun.cprs.yyt.gateway.response.BussinessParamResponse;
import com.hundsun.cprs.yyt.gateway.response.DiliveryAddressListResponse;
import com.hundsun.cprs.yyt.gateway.response.GoodsClassifyJsonResponse;
import com.hundsun.cprs.yyt.gateway.response.GoodsListResponse;
import com.hundsun.cprs.yyt.gateway.response.GoodsResponse;
import com.hundsun.cprs.yyt.gateway.response.OpenFlagResponse;
import com.hundsun.cprs.yyt.gateway.response.PlateListResponse;
import com.hundsun.cprs.yyt.gateway.response.PlateResponse;
import com.hundsun.cprs.yyt.gateway.response.ReturnGoodsListResponse;
import com.hundsun.cprs.yyt.gateway.response.ReturnGoodsResponse;
import com.hundsun.cprs.yyt.gateway.response.TradeMatchDetailListResponse;
import com.hundsun.cprs.yyt.gateway.response.kuaidi100SynQueryDataResponse;
import com.hundsun.cprs.yyt.gateway.service.trade.TradeCommonService;
import com.hundsun.cprs.yyt.gateway.util.VoBeanUtils;
import com.hundsun.cprs.yyt.gateway.vo.DiliveryAddressVo;
import com.hundsun.cprs.yyt.gateway.vo.GoodsClassifyVo;
import com.hundsun.cprs.yyt.gateway.vo.GoodsExtBaseVo;
import com.hundsun.cprs.yyt.gateway.vo.GoodsImageVo;
import com.hundsun.cprs.yyt.gateway.vo.GoodsInfoVo;
import com.hundsun.cprs.yyt.gateway.vo.GoodsSpecsVo;
import com.hundsun.cprs.yyt.gateway.vo.ImageVo;
import com.hundsun.cprs.yyt.gateway.vo.PlateVo;
import com.hundsun.cprs.yyt.gateway.vo.QuotaVo;
import com.hundsun.cprs.yyt.gateway.vo.ReturnGoodsVo;
import com.hundsun.cprs.yyt.gateway.vo.TradeMatchDetailVo;
import com.hundsun.cprs.yyt.service.classify.domain.Classify;
import com.hundsun.cprs.yyt.service.classify.service.ClassifyService;
import com.hundsun.cprs.yyt.service.common.dto.UserAccountDTO;
import com.hundsun.cprs.yyt.service.common.service.RemoteUserService;
import com.hundsun.cprs.yyt.service.dilivery.domain.Delivery;
import com.hundsun.cprs.yyt.service.dilivery.domain.DiliveryAddress;
import com.hundsun.cprs.yyt.service.dilivery.domain.query.SynQuery;
import com.hundsun.cprs.yyt.service.dilivery.enums.EnumDiliveryType;
import com.hundsun.cprs.yyt.service.dilivery.service.DeliveryService;
import com.hundsun.cprs.yyt.service.dilivery.service.DiliveryAddressService;
import com.hundsun.cprs.yyt.service.dilivery.service.Kuaidi100Service;
import com.hundsun.cprs.yyt.service.form.dto.FormInfo;
import com.hundsun.cprs.yyt.service.form.enums.EnumFormAttrMeta;
import com.hundsun.cprs.yyt.service.form.service.FormFacadeService;
import com.hundsun.cprs.yyt.service.goods.domain.GoodsSpecs;
import com.hundsun.cprs.yyt.service.goods.domain.query.GoodsQuery;
import com.hundsun.cprs.yyt.service.goods.dto.GoodsInfo;
import com.hundsun.cprs.yyt.service.goods.enums.EnumGoodsStatus;
import com.hundsun.cprs.yyt.service.goods.service.GoodsCacheQueryService;
import com.hundsun.cprs.yyt.service.goods.service.GoodsService;
import com.hundsun.cprs.yyt.service.goods.service.GoodsSkuService;
import com.hundsun.cprs.yyt.service.order.dto.OrderInfo;
import com.hundsun.cprs.yyt.service.order.service.OrderService;
import com.hundsun.cprs.yyt.service.plate.domain.PlateInfo;
import com.hundsun.cprs.yyt.service.plate.domain.query.PlateQuery;
import com.hundsun.cprs.yyt.service.plate.service.PlateService;
import com.hundsun.cprs.yyt.service.quota.domain.Quota;
import com.hundsun.cprs.yyt.service.quota.service.QuotaService;
import com.hundsun.cprs.yyt.service.system.domain.BussinessParam;
import com.hundsun.cprs.yyt.service.system.dto.TradingTimePeriodReponse;
import com.hundsun.cprs.yyt.service.system.service.BussinessParamService;
import com.hundsun.cprs.yyt.service.system.service.TradingTimePeriodService;
import com.hundsun.cprs.yyt.service.trade.domain.ReturnGoodsFlow;
import com.hundsun.cprs.yyt.service.trade.domain.TradeMatchDetail;
import com.hundsun.cprs.yyt.service.trade.domain.query.ReturnGoodsFlowQuery;
import com.hundsun.cprs.yyt.service.trade.dto.MatchRequest;
import com.hundsun.cprs.yyt.service.trade.enums.EnumEntustBSType;
import com.hundsun.cprs.yyt.service.trade.service.ReturnGoodsFlowService;
import com.hundsun.cprs.yyt.service.trade.service.TradeMatchDetailService;
import com.hundsun.cprs.yyt.util.BeanUtils;

@Service
public class TradeCommonServiceImpl extends BaseService implements TradeCommonService {

    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private PlateService plateService;

    @Autowired
    private ClassifyService classifyService;

    @Autowired
    private DiliveryAddressService diliveryAddressService;

    @Autowired
    private BussinessParamService bussinessParamService;

    @Autowired
    private FormFacadeService formFacadeService;

    @Autowired
    private GoodsService goodsService;
    
    @Autowired
    private GoodsCacheQueryService goodsCacheQueryService;

    @Autowired
    private GoodsSkuService goodsSkuService;

    @Autowired
    private TradingTimePeriodService tradingTimePeriodService;

    @Autowired
    private TradeMatchDetailService tradeMatchDetailService;

    @Autowired
    private Kuaidi100Service kuaidi100Service;

    @Autowired
    private OrderService orderService;

    @Autowired
    private DeliveryService deliveryService;

    @Autowired
    private ReturnGoodsFlowService flowService;
    
    @Autowired
    private QuotaService quotaService;

    @Override
    public PlateListResponse getPlateList(PlateRequest request) {
        PlateListResponse response = new PlateListResponse();
        try {
            Validate.notNull(request, "参数非法");
            Validate.notNull(request.getAreaCode(), "区编码必填");
            //统计热购标识
            boolean statBidflag = request.getStatBid() == 0 ? false : true;
            PlateQuery query = new PlateQuery();
            query.setPageNo(request.getPageNo());
            query.setPageSize(request.getPageSize());
            query.setAreaCode(request.getAreaCode());
            query.setPlateCode(request.getPlateCode());
            plateService.selectPlateByPage(query);
            if (query.getTotalCount() > 0) {
                response.setTotalCount(query.getTotalCount());
                response.setResult(BeanUtils.batchTransform(PlateVo.class, query.getData()));
            }
        } catch (IllegalArgumentException e) {
            response.setErrorNo(EnumBusinessCode.BUSINESS_1000.getErrorNo());
            response.setErrorInfo(e.getMessage());
        } catch (Exception e) {
            logger.error("处理异常", e);
            response.setErrorNo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorNo());
            response.setErrorInfo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorInfo());
        }
        return response;
    }

    @Override
    public PlateResponse getPlateDetail(Long plateId) {
        PlateResponse response = new PlateResponse();
        try {
            Validate.notNull(plateId, "参数非法");
            PlateInfo plate = plateService.selectPlateInfoById(plateId);
            if (plate == null) {
                throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1006.getErrorNo(), "专场信息不存在");
            }
            PlateVo result = BeanUtils.transfrom(PlateVo.class, plate);
            if (CollectionUtils.isNotEmpty(plate.getImageList())) {
                result.setImageList(BeanUtils.batchTransform(ImageVo.class, plate.getImageList()));
            }
            if (CollectionUtils.isNotEmpty(plate.getFormAttrValueList())) {
                //有动态属性值
                FormInfo form = formFacadeService.getFormInfoByCode(PlateService.DYNAMIC_FORM_CODE);
                if (form != null) {
                    form.loadValues(plate.getFormAttrValueList());
                    result.setTradeLimitInVip(form.getAttrValue(EnumFormAttrMeta.TRADE_LIMIT_IN_VIP.getAttrKey()));
                    result.setTradeLimitOption(form.getAttrValue(EnumFormAttrMeta.TRADE_LIMIT_OPTION.getAttrKey()));
                }
            }
            response.setResult(result);
        } catch (IllegalArgumentException e) {
            response.setErrorNo(EnumBusinessCode.BUSINESS_1000.getErrorNo());
            response.setErrorInfo(e.getMessage());
        } catch (ServiceCodeException e) {
            response.setErrorNo(e.getErrorCode());
            response.setErrorInfo(e.getErrorDesc());
        } catch (Exception e) {
            logger.error("处理异常", e);
            response.setErrorNo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorNo());
            response.setErrorInfo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorInfo());
        }
        return response;
    }

    @Override
    public GoodsClassifyJsonResponse getAllClassifyByJson() {
        GoodsClassifyJsonResponse response = new GoodsClassifyJsonResponse();
        try {
            List<Classify> firstTypeOfClassifyList = classifyService.selectOneClassify("N");
            if (CollectionUtils.isNotEmpty(firstTypeOfClassifyList)) {
                List<GoodsClassifyVo> classifyVoList = BeanUtils.batchTransform(GoodsClassifyVo.class, firstTypeOfClassifyList);
                for (GoodsClassifyVo firstClassify : classifyVoList) {
                    List<Classify> secondTypeOfClassifyList = classifyService.selectTwoClassifyByParentId(firstClassify.getId(), "N");
                    firstClassify.setChildList(BeanUtils.batchTransform(GoodsClassifyVo.class, secondTypeOfClassifyList));
                }
                response.setResult(JSONObject.toJSONString(classifyVoList));
            }
        } catch (Exception e) {
            logger.error("处理异常", e);
            response.setErrorNo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorNo());
            response.setErrorInfo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorInfo());
        }
        return response;
    }
    @Override
    public DiliveryAddressListResponse getDiliveryAddressList(Long userId,String type) {
        DiliveryAddressListResponse response = new DiliveryAddressListResponse();
        try {
            Validate.notNull(userId, "用户信息必填");
            Validate.notNull(type, "类型必填");
            //非自提需要校验用户时候一致
            if (!type.equals(EnumDiliveryType.SELFTGET.getValue())) {
                UserAccountDTO userInfo = remoteUserService.getUserDetailByUserId(userId);
                if (userInfo == null) {
                    throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1001.getErrorNo(), EnumBusinessCode.BUSINESS_1001.getErrorInfo());
                }
            }else{
                //自提地址userId转换
                userId = 0L;
            }
            List<DiliveryAddress> result = diliveryAddressService.selectAddressListByUserId(userId);
            if (CollectionUtils.isNotEmpty(result)) {
                response.setResult(BeanUtils.batchTransform(DiliveryAddressVo.class, result));
            }
        } catch (IllegalArgumentException e) {
            response.setErrorNo(EnumBusinessCode.BUSINESS_1000.getErrorNo());
            response.setErrorInfo(e.getMessage());
        } catch (ServiceCodeException e) {
            response.setErrorNo(e.getErrorCode());
            response.setErrorInfo(e.getMessage());
        } catch (Exception e) {
            logger.error("处理异常", e);
            response.setErrorNo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorNo());
            response.setErrorInfo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorInfo());
        }
        return response;
    }

    @Override
    public BaseResponse createDiliveryAddress(DiliveryAddressRequest request) {
        BaseResponse response = new BaseResponse();
        try {
            Validate.notNull(request, "请求参数必填");
            Validate.notNull(request.getUserId(), "用户信息必填");
            Validate.notNull(request.getCountyAddress(), "区级地址必填");
            Validate.notNull(request.getCountyCode(), "用户信息必填");
            Validate.notNull(request.getProvinceAddress(), "省级地址必填");
            Validate.notNull(request.getProvinceCode(), "省级code必填");
            Validate.notNull(request.getMunicipalAddress(), "市级地址必填");
            Validate.notNull(request.getMunicipalCode(), "市级code必填");
            Validate.notNull(request.getDiliveryAddress(), "详细地址必填");
            Validate.notNull(request.getPhone(), "收货人联系电话必填");
            UserAccountDTO userInfo = remoteUserService.getUserDetailByUserId(request.getUserId());
            if (userInfo == null) {
                throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1001.getErrorNo(), EnumBusinessCode.BUSINESS_1001.getErrorInfo());
            }
            DiliveryAddress diliveryAddress = BeanUtils.transfrom(DiliveryAddress.class, request);
            diliveryAddress.setConsigneeName(request.getConsigneeName());
            diliveryAddressService.createDiliveryAddress(diliveryAddress);
        } catch (IllegalArgumentException e) {
            response.setErrorNo(EnumBusinessCode.BUSINESS_1000.getErrorNo());
            response.setErrorInfo(e.getMessage());
        } catch (ServiceCodeException e) {
            response.setErrorNo(e.getErrorCode());
            response.setErrorInfo(e.getMessage());
        } catch (Exception e) {
            logger.error("处理异常", e);
            response.setErrorNo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorNo());
            response.setErrorInfo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorInfo());
        }
        return response;
    }

    @Override
    public BaseResponse modifyDiliveryAddress(DiliveryAddressRequest request) {
        BaseResponse response = new BaseResponse();
        try {
            Validate.notNull(request, "请求参数必填");
            Validate.notNull(request.getUserId(), "用户信息必填");
            Validate.notNull(request.getCountyAddress(), "区级地址必填");
            Validate.notNull(request.getCountyCode(), "用户信息必填");
            Validate.notNull(request.getProvinceAddress(), "省级地址必填");
            Validate.notNull(request.getProvinceCode(), "省级code必填");
            Validate.notNull(request.getMunicipalAddress(), "市级地址必填");
            Validate.notNull(request.getMunicipalCode(), "市级code必填");
            Validate.notNull(request.getDiliveryAddress(), "详细地址必填");
            Validate.notNull(request.getPhone(), "收货人联系电话必填");
            Validate.notNull(request.getDiliveryAddressId(), "收货地址信息必填");
            UserAccountDTO userInfo = remoteUserService.getUserDetailByUserId(request.getUserId());
            if (userInfo == null) {
                throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1001.getErrorNo(), EnumBusinessCode.BUSINESS_1001.getErrorInfo());
            }
            DiliveryAddress diliveryAddress = BeanUtils.transfrom(DiliveryAddress.class, request);
            diliveryAddress.setId(request.getDiliveryAddressId());
            diliveryAddress.setConsigneeName(request.getConsigneeName());
            diliveryAddressService.modifiyDiliveryAddress(diliveryAddress);
        } catch (IllegalArgumentException e) {
            response.setErrorNo(EnumBusinessCode.BUSINESS_1000.getErrorNo());
            response.setErrorInfo(e.getMessage());
        } catch (ServiceCodeException e) {
            response.setErrorNo(e.getErrorCode());
            response.setErrorInfo(e.getMessage());
        } catch (Exception e) {
            logger.error("处理异常", e);
            response.setErrorNo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorNo());
            response.setErrorInfo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorInfo());
        }
        return response;
    }

    @Override
    public BaseResponse deleteDiliveryAddress(Long userId, Long diliveryAddressId) {
        BaseResponse response = new BaseResponse();
        try {
            Validate.notNull(userId, "用户信息必填");
            Validate.notNull(diliveryAddressId, "收货地址ID必填");
            diliveryAddressService.deleteDiliveryAddress(userId, diliveryAddressId);
        } catch (IllegalArgumentException e) {
            response.setErrorNo(EnumBusinessCode.BUSINESS_1000.getErrorNo());
            response.setErrorInfo(e.getMessage());
        } catch (ServiceCodeException e) {
            response.setErrorNo(e.getErrorCode());
            response.setErrorInfo(e.getMessage());
        } catch (Exception e) {
            logger.error("处理异常", e);
            response.setErrorNo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorNo());
            response.setErrorInfo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorInfo());
        }
        return response;
    }

    @Override
    public BussinessParamResponse getBussinessValueByKey(BussinessParamRequest request) {
        BussinessParamResponse response = new BussinessParamResponse();
        try {
            Validate.notNull(request, "请求参数必填");
            Validate.notNull(request.getBussinessKey(), "查询键名必填");
            BussinessParam bussinessParam=bussinessParamService.getBussinessParamByKey(request.getBussinessKey());
            if(bussinessParam==null){
                throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1023.getErrorNo(),EnumBusinessCode.BUSINESS_1023.getErrorInfo());
            }
            response.setBussinessValue(bussinessParam.getBussinessValue());
        } catch (IllegalArgumentException e) {
            response.setErrorNo(EnumBusinessCode.BUSINESS_1000.getErrorNo());
            response.setErrorInfo(e.getMessage());
        } catch (ServiceCodeException e) {
            response.setErrorNo(e.getErrorCode());
            response.setErrorInfo(e.getMessage());
        } catch (Exception e) {
            logger.error("处理异常", e);
            response.setErrorNo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorNo());
            response.setErrorInfo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorInfo());
        }
        return response;
    }

    @Override
    public GoodsListResponse getGoodsListByPlate(GoodsRequest request) {
        GoodsListResponse response = new GoodsListResponse();
        try {
            Validate.notNull(request, "请求参数必填");
            Validate.notNull(request.getPlateId(), "专场信息必填");
            Validate.notNull(request.getAreaCode(), "区信息必填");
            GoodsQuery query = BeanUtils.transfrom(GoodsQuery.class,request);
            query.setStatus(EnumGoodsStatus.PUBLISHED.getCode());//前端只展示已上架的商品
            //goodsService.queryGoodsPlateList(query);
            goodsCacheQueryService.selectByPage(query);
            if (CollectionUtils.isNotEmpty(query.getData())) {
                //fillExtendsData(request,response,query);
                List<GoodsExtBaseVo> goodsExtBaseVoList = VoBeanUtils.copyPropertiesFrom(query.getData());
                if (request.getAreaCode().equals(EnumAreaCode.WHOLESALE_AREA.getCode())){
                    replaceLowestCostPrice(goodsExtBaseVoList);
                }
                response.setResult(goodsExtBaseVoList);
                response.setTotalCount(query.getTotalCount());
            }
        } catch (IllegalArgumentException e) {
            response.setErrorNo(EnumBusinessCode.BUSINESS_1000.getErrorNo());
            response.setErrorInfo(e.getMessage());
        } catch (ServiceCodeException e) {
            response.setErrorNo(e.getErrorCode());
            response.setErrorInfo(e.getMessage());
        } catch (Exception e) {
            logger.error("处理异常", e);
            response.setErrorNo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorNo());
            response.setErrorInfo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorInfo());
        }
        return response;
    }

    @Override
    public GoodsListResponse getGoodsListByClassify(GoodsRequest request) {
        GoodsListResponse response = new GoodsListResponse();
        try {
            Validate.notNull(request, "请求参数必填");
            Validate.notNull(request.getClassifyId(), "分类信息必填");
            Validate.notNull(request.getAreaCode(), "区信息必填");
            GoodsQuery query = BeanUtils.transfrom(GoodsQuery.class,request);
            query.setStatus(EnumGoodsStatus.PUBLISHED.getCode());//前端只展示已上架的商品
            goodsService.queryGoodsClassifyList(query);
            if (query.getTotalCount() > 0) {
                fillExtendsData(request,response,query);
            }
        } catch (IllegalArgumentException e) {
            response.setErrorNo(EnumBusinessCode.BUSINESS_1000.getErrorNo());
            response.setErrorInfo(e.getMessage());
        } catch (ServiceCodeException e) {
            response.setErrorNo(e.getErrorCode());
            response.setErrorInfo(e.getMessage());
        } catch (Exception e) {
            logger.error("处理异常", e);
            response.setErrorNo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorNo());
            response.setErrorInfo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorInfo());
        }
        return response;
    }

    @Override
    public GoodsResponse getGoodsDetail(GoodsRequest request) {
        GoodsResponse response = new GoodsResponse();
        try {
            Validate.notNull(request, "请求参数必填");
            Validate.notNull(request.getGoodsId(), "商品信息必填");
            Validate.notNull(request.getAreaCode(), "区编码必填");
            GoodsInfo goodsInfo = goodsService.selectGoodsInfoByIdFromCache(request.getGoodsId().intValue(),request.getAreaCode());
            if (goodsInfo == null){
                throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1102.getErrorNo(),EnumBusinessCode.BUSINESS_1102.getErrorInfo());
            }
            
            //实时查下库存信息，替换商品返回
            List<GoodsSpecs> goodsSpecsList = goodsSkuService.selectGoodsSpecsList(request.getGoodsId().intValue(),request.getAreaCode(),request.getPlateCode());
            goodsInfo.setSkus(goodsSpecsList);
            
            GoodsInfoVo goodsInfoVo = VoBeanUtils.copyPropertiesFromExt(goodsInfo);
            goodsInfoVo.setAreaCode(request.getAreaCode());
            
            //附加奖励配额及支付配额简单信息
            if (EnumAreaCode.RETAIL_AREA.getCode().equals(goodsInfoVo.getAreaCode())) {
            	Quota quota = quotaService.selectQuoteById(goodsInfo.getRewardQuotaId());
            	if (quota != null) {
            		goodsInfoVo.setRewardQuota(new QuotaVo(quota.getId(),quota.getName(),quota.getType()));
				}
			} else if(EnumAreaCode.WHOLESALE_AREA.getCode().equals(goodsInfoVo.getAreaCode())) {
				Quota quota = quotaService.selectQuoteById(goodsInfo.getPayQuotaId());
            	if (quota != null) {
            		goodsInfoVo.setPayQuota(new QuotaVo(quota.getId(),quota.getName(),quota.getType()));
				}
			}
            
            response.setResult(goodsInfoVo);
        } catch (IllegalArgumentException e) {
            response.setErrorNo(EnumBusinessCode.BUSINESS_1000.getErrorNo());
            response.setErrorInfo(e.getMessage());
        } catch (ServiceCodeException e) {
            response.setErrorNo(e.getErrorCode());
            response.setErrorInfo(e.getMessage());
        } catch (Exception e) {
            logger.error("处理异常", e);
            response.setErrorNo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorNo());
            response.setErrorInfo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorInfo());
        }
        return response;
    }

    @Override
    public GoodsListResponse getGoodsListByArea(GoodsRequest request) {
        GoodsListResponse response = new GoodsListResponse();
        try {
            Validate.notNull(request, "请求参数必填");
            Validate.notNull(request.getAreaCode(), "区信息必填");
            GoodsQuery query = BeanUtils.transfrom(GoodsQuery.class,request);
            query.setStatus(EnumGoodsStatus.PUBLISHED.getCode());//前端只展示已上架的商品
            if (request.getPayQuotaId() != null) {
            	goodsService.queryAreaGoodsList(query);
            	if (CollectionUtils.isNotEmpty(query.getData())) {
            		fillExtendsData(request, response, query);
            	}
			} else {
				goodsCacheQueryService.selectByPage(query);
				
				if (CollectionUtils.isNotEmpty(query.getData())) {
	                //fillExtendsData(request, response, query);
	                List<GoodsExtBaseVo> goodsExtBaseVoList = VoBeanUtils.copyPropertiesFrom(query.getData());
	                if (request.getAreaCode().equals(EnumAreaCode.WHOLESALE_AREA.getCode())){
	                    replaceLowestCostPrice(goodsExtBaseVoList);
	                }
	                response.setResult(goodsExtBaseVoList);
	                response.setTotalCount(query.getTotalCount());
	            }
			}
        } catch (IllegalArgumentException e) {
            response.setErrorNo(EnumBusinessCode.BUSINESS_1000.getErrorNo());
            response.setErrorInfo(e.getMessage());
        } catch (ServiceCodeException e) {
            response.setErrorNo(e.getErrorCode());
            response.setErrorInfo(e.getMessage());
        } catch (Exception e) {
            logger.error("处理异常", e);
            response.setErrorNo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorNo());
            response.setErrorInfo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorInfo());
        }
        return response;
    }
    
    /**
     * 市场价替换为最低价格
     * @param goodsList
     */
    protected void replaceLowestCostPrice(List<GoodsExtBaseVo> goodsList){
        if (goodsList == null) {
            return;
        }
        
        for(GoodsExtBaseVo temp : goodsList){
            if (CollectionUtils.isNotEmpty(temp.getGoodsSpecsVoList())) {
                long lowestCostPrice = temp.getGoodsSpecsVoList().get(0).getGoodsPrice();
                for (GoodsSpecsVo goodsSpecs:temp.getGoodsSpecsVoList()){
                    if (goodsSpecs.getGoodsPrice().longValue()<lowestCostPrice){
                        lowestCostPrice = goodsSpecs.getGoodsPrice();
                    }
                }
                temp.setCostPrice(lowestCostPrice);
            }
        }
    }

    /**
     * 填充图片等辅助信息
     *
     * */
    public void fillExtendsData(GoodsRequest request,GoodsListResponse response,GoodsQuery query){
        response.setTotalCount(query.getTotalCount());
        goodsService.fillGoodsImageList(query.getData());
        List<GoodsExtBaseVo> goodsExtBaseVoList = new ArrayList<>();
        for (GoodsInfo goodsInfo : query.getData()){
            GoodsExtBaseVo goodsExtBaseVo = BeanUtils.transfrom(GoodsExtBaseVo.class,goodsInfo);
            if (goodsInfo.getGoodsPrice() != null){
                goodsExtBaseVo.setGoodsPrice(goodsInfo.getGoodsPrice().longValue());
            }
            goodsExtBaseVo.setCostPrice(goodsInfo.getCostPrice().longValue());
            goodsExtBaseVo.setGoodsImageVoList(BeanUtils.batchTransform(GoodsImageVo.class,goodsInfo.getImageList()));
            if (request.getAreaCode().equals(EnumAreaCode.WHOLESALE_AREA.getCode())){
                //批发区的商品需要把规格里的最低价返回给前端
                List<GoodsSpecs> goodsSpecsList = goodsSkuService.selectGoodsSpecsList(goodsInfo.getId(),request.getAreaCode(),request.getPlateCode());
                if (!goodsSpecsList.isEmpty()){
                    goodsExtBaseVo.setCostPrice(goodsSpecsList.get(0).getGoodsPrice().longValue());
                    for (GoodsSpecs goodsSpecs:goodsSpecsList){
                        if (goodsSpecs.getGoodsPrice().longValue()<goodsExtBaseVo.getCostPrice()){
                            goodsExtBaseVo.setCostPrice(goodsSpecs.getGoodsPrice().longValue());
                        }
                    }
                }
            }
            goodsExtBaseVoList.add(goodsExtBaseVo);
        }
        response.setResult(goodsExtBaseVoList);
    }

    @Override
    public OpenFlagResponse isTradingTimePeriod() {
        OpenFlagResponse response = new OpenFlagResponse();
        try {
            TradingTimePeriodReponse tradingTimePeriodReponse = tradingTimePeriodService.isTradingTimePeriod();
            if (tradingTimePeriodReponse.getFlag()){
                response.setOpenFlag("Y");
            }else{
                response.setOpenFlag("N");
            }
        } catch (IllegalArgumentException e) {
            response.setErrorNo(EnumBusinessCode.BUSINESS_1000.getErrorNo());
            response.setErrorInfo(e.getMessage());
        } catch (ServiceCodeException e) {
            response.setErrorNo(e.getErrorCode());
            response.setErrorInfo(e.getMessage());
        } catch (Exception e) {
            logger.error("处理异常", e);
            response.setErrorNo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorNo());
            response.setErrorInfo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorInfo());
        }
        return response;
    }

    @Override
    public TradeMatchDetailListResponse getTradeMatchDetailByGoods(TradeMatchDetailRequest request) {
        TradeMatchDetailListResponse response = new TradeMatchDetailListResponse();
        try {
            Validate.notNull(request.getGoodsId(), "商品id必填");
            GoodsInfo goodsInfo = goodsService.selectGoodsInfoById(request.getGoodsId().intValue());
            MatchRequest matchRequest = new MatchRequest();
            matchRequest.setCount(request.getPageSize());
            matchRequest.setEntrustBs(EnumEntustBSType.SELL.getCode());
            matchRequest.setGoodsCode(goodsInfo.getGoodsCode());
            List<TradeMatchDetail> tradeMatchDetailList = tradeMatchDetailService.getLastDetail(matchRequest);
            if (CollectionUtils.isNotEmpty(tradeMatchDetailList)){
                response.setTotalCount(tradeMatchDetailList.size());
                List<TradeMatchDetailVo> tradeMatchDetailVoList = new ArrayList<>();
                for (TradeMatchDetail tradeMatchDetail:tradeMatchDetailList){
                    TradeMatchDetailVo tradeMatchDetailVo = new TradeMatchDetailVo();
                    tradeMatchDetailVo.setUserName(tradeMatchDetail.getEntrust().getUserName());
                    tradeMatchDetailVo.setMatchFundAmount(tradeMatchDetail.getMatchFundAmount());
                    tradeMatchDetailVo.setMatchAmount(tradeMatchDetail.getMatchAmount());
                    tradeMatchDetailVo.setFundAccount(tradeMatchDetail.getEntrust().getFundAccount());
                    tradeMatchDetailVo.setEntrustNo(tradeMatchDetail.getEntrust().getEntrustNo());
                    tradeMatchDetailVo.setGmtCreate(tradeMatchDetail.getGmtCreate());
                    tradeMatchDetailVoList.add(tradeMatchDetailVo);
                }
                response.setTradeMatchDetailVoList(tradeMatchDetailVoList);
            }
        } catch (IllegalArgumentException e) {
            response.setErrorNo(EnumBusinessCode.BUSINESS_1000.getErrorNo());
            response.setErrorInfo(e.getMessage());
        } catch (ServiceCodeException e) {
            response.setErrorNo(e.getErrorCode());
            response.setErrorInfo(e.getMessage());
        } catch (Exception e) {
            logger.error("处理异常", e);
            response.setErrorNo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorNo());
            response.setErrorInfo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorInfo());
        }
        return response;
    }

    @Override
    public kuaidi100SynQueryDataResponse synQueryData(kuaidi100SynQueryDataRequest request) {
        kuaidi100SynQueryDataResponse response = new kuaidi100SynQueryDataResponse();
        try {
            // 参数校验
            Assert.notNull(request,"参数不能为空");
            Assert.notNull(request.getOrderId(),"订单id不能为空");
            Assert.notNull(request.getUserId(),"用户信息不能为空");
            //校验订单所属用户和查询用户是否相同
            OrderInfo orderInfo = orderService.selectOrderInfoById(request.getOrderId());
            if (orderInfo == null){
                throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1501.getErrorNo(),EnumBusinessCode.BUSINESS_1501.getErrorInfo());
            }
            if (orderInfo.getUserId().compareTo(request.getUserId()) != 0){
                throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1522.getErrorNo(),EnumBusinessCode.BUSINESS_1522.getErrorInfo());
            }
            //根据订单id查询物流信息
            Delivery delivery = deliveryService.selectDeliveryInfo(request.getOrderId());
            if (delivery == null){
                return response;
            }
            //组装物流信息查询条件
            SynQuery synQuery = new SynQuery();
            synQuery.setCom(delivery.getCompanyCode());
            synQuery.setNum(delivery.getBatchNumber());
            String result = kuaidi100Service.synQueryData(synQuery);
            response.setResult(result);
        } catch (IllegalArgumentException e) {
            response.setErrorNo(EnumBusinessCode.BUSINESS_1000.getErrorNo());
            response.setErrorInfo(e.getMessage());
        } catch (ServiceCodeException e) {
            response.setErrorNo(e.getErrorCode());
            response.setErrorInfo(e.getMessage());
        } catch (Exception e) {
            logger.error("处理异常", e);
            response.setErrorNo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorNo());
            response.setErrorInfo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorInfo());
        }
        return response;
    }

    @Override
    public ReturnGoodsListResponse queryReturnBackList(ReturnGoodsRequest request) {
        ReturnGoodsListResponse response = new ReturnGoodsListResponse();
        try {
            // 参数校验
            Assert.notNull(request,"参数不能为空");
            Assert.notNull(request.getUserId(),"用户信息不能为空");
            ReturnGoodsFlowQuery query = BeanUtils.transfrom(ReturnGoodsFlowQuery.class,request);
            flowService.queryByPage(query);
            if (query.getTotalCount() > 0){
                response.setTotalCount(query.getTotalCount());
                response.setReturnGoodsVos(BeanUtils.batchTransform(ReturnGoodsVo.class,query.getData()));
            }
        } catch (IllegalArgumentException e) {
            response.setErrorNo(EnumBusinessCode.BUSINESS_1000.getErrorNo());
            response.setErrorInfo(e.getMessage());
        } catch (ServiceCodeException e) {
            response.setErrorNo(e.getErrorCode());
            response.setErrorInfo(e.getMessage());
        } catch (Exception e) {
            logger.error("处理异常", e);
            response.setErrorNo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorNo());
            response.setErrorInfo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorInfo());
        }
        return response;
    }

    @Override
    public ReturnGoodsResponse queryReturnBackDetail(Long userId, Long returnGoodsId) {
        ReturnGoodsResponse response = new ReturnGoodsResponse();
        try {
            // 参数校验
            Assert.notNull(userId,"用户信息不能为空");
            Assert.notNull(returnGoodsId,"退货信息不能为空");
            ReturnGoodsFlow returnGoodsFlow = flowService.getReturnGoodsFlowById(returnGoodsId);
            if (returnGoodsFlow != null && returnGoodsFlow.getUserId().equals(userId)){
                response.setReturnGoodsVo(BeanUtils.transfrom(ReturnGoodsVo.class,returnGoodsFlow));
            }
        } catch (IllegalArgumentException e) {
            response.setErrorNo(EnumBusinessCode.BUSINESS_1000.getErrorNo());
            response.setErrorInfo(e.getMessage());
        } catch (ServiceCodeException e) {
            response.setErrorNo(e.getErrorCode());
            response.setErrorInfo(e.getMessage());
        } catch (Exception e) {
            logger.error("处理异常", e);
            response.setErrorNo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorNo());
            response.setErrorInfo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorInfo());
        }
        return response;
    }
}
